package com.hiv.filter;


import com.hiv.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.session.Session;
import org.springframework.session.SessionRepository;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * cookie过滤器
 */
@Slf4j
@Order(-1)
@Component
public class CookieFilter implements Filter {

  @Autowired
  private SessionRepository sessionRepository;

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    String sessionid = request.getParameter(Constants.SESSIONID);
    if(!StringUtils.isEmpty(sessionid)){
      Session session = sessionRepository.findById(sessionid);
      Cookie cookie = new Cookie(Constants.SESSIONID, sessionid);
      cookie.setPath("/");
      cookie.setMaxAge(86400);
      res.addCookie(cookie);
      req.getSession().setAttribute(Constants.LOGIN_USER, session.getAttribute(Constants.LOGIN_USER));
    }
    chain.doFilter(request, response);
  }

}